<template>
	<view v-if="pageType=='query'||pageType=='seller'">
		<u-navbar titleStyle="font-size:20px;font-weight:600" style="max-width: 700px;" :leftIconSize='0'
			:placeholder='true' :title="pageType=='seller'?'服务商登录':'学员登录'" />
		<view class="u-button-login">
			<!-- <u-toast ref="uToast" /> -->
			<view class="login-title">
				<view class="" style="position: relative;">
					<image style="width: 70px;height: 70px;" :src="projectCode === 'JPQ'? logoUrl : otherLogoUrl"
						mode=""></image>
					<view class="tip-bg">
						<view class="" style="width:100%;height:100%;position: relative;">
							<image style="width:100%;height:100%" src="@/static/image/login/tip-blue-bg.png" mode="">
							</image>
							<text>{{pageType=='seller'?'服务商':'学员端'}}</text>
						</view>
					</view>
				</view>
				<image style="width: 154px;height: 60px;margin-top: 25px;" src="@/static/image/logintitle.png" mode="">
				</image>
			</view>
			<view class='u-submit-form' style="position: relative">
				<u-input :maxlength="11" v-if="pageType=='seller'"
					:customStyle="{background:'#fff',border:'none',width: '92%',padding:'13px 15px'}"
					style="max-width: 700px;" v-model="formsubmit.mobile" placeholder='请输入手机号' />
				<u-input :maxlength="18" v-else
					:customStyle="{background:'#fff',border:'none',width: '92%',padding:'13px 15px'}"
					style="max-width: 700px;" v-model="formsubmit.idCard" placeholder='请输入身份证号或手机号' />
				<!--  -->
				<!--				<view v-if="genderList[0].length>1 && pageType==='query'" class="selectView" @click="show = true">{{courseName}}</view>-->
				<u-input
					:customStyle="{background:'#fff',border:'none',width: '92%','margin-top':'40rpx',padding:'13px 15px'}"
					style="max-width: 700px;" v-model="formsubmit.password" type="password"
					placeholder='请输入密码(默认后六位)' />
				<!--				 <view class="forget-password" @click="$routePage({url: 'pages/login/components/register'})">-->
				<!--					注册</view>-->
				<!--				<view class="forget-password" v-if="pageType=='seller'" @click="pageType='forget-word'">-->
				<!--					<text>忘记密码？</text>-->
				<!--				</view>-->
				<view class="forget-password" v-if="pageType=='seller'"
					@click="$routePage({url: 'pages/login/components/forget-password', params: {type: 'reset', mobile: formsubmit.mobile}})">
					<text>忘记密码？</text>
				</view>
				<!--        <view v-if="pageType=='query'" style="width: 100%;text-align: right; color: #D3D3D3;"-->
				<!--              @click="$routePage({url: 'pages/login/components/register', params: {type: 'student'}})">-->
				<!--          <text>免费注册</text>-->
				<!--        </view>-->
			</view>
			<u-picker @confirm='confirmChange' @cancel='show=false' @close='show=false' :show="show"
				:keyName="'courseName'" :columns="genderList" :closeOnClickOverlay='closeOnClickOverlay'></u-picker>
			<u-button type="primary" shape='circle' style="max-width: 600px;"
				:customStyle="{width: '92%',height:'44px','font-size':'17px',border:'none'}"
				@click='submitLogin'>登录</u-button>
			<view class="seller-button" @click="pageHandle()">{{pageType=='seller'?'学员登录':'题库购买'}}</view>
			<u-modal :show="showConfirmDialog" title="提示" :showCancelButton="true" @cancel="dialogCancelHandle"
				content='是否确认绑定当前微信号,绑定后只允许该微信号登录' @confirm="dialogConfirmHandle"></u-modal>
		</view>
	</view>
	<!-- 忘记密码 -->
	<!--	<ForgetPassword @customBack="pageType=pageTypeSave" :transferInfo="{mobile:formsubmit.mobile}"-->
	<!--		v-if="pageType=='forget-word'"></ForgetPassword>-->
</template>
<script setup>
	import ForgetPassword from './components/forget-password'
	import {
		reactive,
		ref,
		getCurrentInstance,
		watch,
		onMounted
	} from "vue";
	import {
		login,
		coursList,
		saleLogin
	} from '@/api/login.js'
	import {
		isIdentityCard
	} from '@/utils/check.js'
	import onShare from '@/utils/share.js';
	import {
		isMobile
	} from '@/utils/validate.js'
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import logoUrl from "@/static/image/logo.png";
	import otherLogoUrl from "@/static/image/logo-zjxt.png";

	const {
		onShareAppMessage,
		onShareTimeline
	} = onShare()
	const {
		proxy
	} = getCurrentInstance()
	const uToast = ref('')
	const pageType = ref('query')
	const pageTypeSave = ref('query')
	const show = ref(false)
	let showConfirmDialog = ref(false)
	// 点击关闭遮罩
	const closeOnClickOverlay = ref(true)
	const courseName = ref('')
	// 350823199102140928
	const formsubmit = reactive({
		idCard: '',
		password: '',
		courseId: '',
		mobile: ''
	})
	// 获取科目
	const genderList = ref([
		[]
	])
	const projectCode = ref('')

	//监听进入忘记密码的登录页面
	watch(() => {
		return pageType.value
	}, (val, old) => {
		val == 'forget-word' ? pageTypeSave.value = old : ''
	}, {})
	onLoad((options) => {
		pageType.value = options.pageType || 'query'
	})

	watch(() => formsubmit.idCard, (val) => {
		formsubmit.password = ''
		// val.length == 18 || val.length == 11 ? (genderList.value[0] = [], idCardChange()) : ''
	})
	onMounted(() => {
		let roueUrl = 'tabBarPages/index/index'
		let JPQUrl = 'pages/index/index'
		let ZJXTUrl = 'pages/index/index-zj'
		uni.getStorageSync('loginType') == 'seller' ? (roueUrl = proxy.getProjectCode() === 'ZJXT' ? ZJXTUrl :
				JPQUrl, pageType.value = 'seller') :
			''
		if (uni.getStorageSync('token')) {
			proxy.$u.route({
				type: 'redirect',
				url: roueUrl
			})
		}
		// 测试模式
		if (formsubmit.idCard) {
			idCardChange()
		}
		projectCode.value = proxy.getProjectCode()
	})
	const idCardChange = () => {
		// if (!isIdentityCard(formsubmit.idCard)) {
		// 	uni.showToast({ title: '身份证有误，请重新输入', duration: 1200, icon: "none" });
		// 	return false
		// }
		if (genderList.value[0].length > 0) {
			return true
		}
		coursList({
			idCard: formsubmit.idCard
		}).then((res) => {
			/*  */
			genderList.value = [
				[]
			]
			if (res.data) {
				res.data.map((item) => {
					console.log(item.status)
					item.status == '2' ? genderList.value[0].push(item) : ''
				})
			}
			if (!res.data) {
				return
			}
			let length = res.data.length
			courseName.value = res.data[length - 1].courseName || ''
			formsubmit.courseId = res.data[length - 1].courseId
		})
		return true
	}
	const pageHandle = () => {
		if (pageType.value == 'query') {
			uni.showModal({
				title: '提示',
				content: '购买功能开源版未开放,如需购买请联系15355084408。',
				confirmText: '拨打',
				success(res) {
					if (res.confirm) {
						uni.makePhoneCall({
							phoneNumber: '15355084408'
						})
					}
				}
			})
			return
		}
		pageType.value == 'query' ? pageType.value = 'seller' : pageType.value = 'query'
		cleanForm(formsubmit)
		//初始化报名科目
		genderList.value[0] = []
	}
	const cleanForm = (obj) => {
		Object.keys(obj).map(key => {
			obj[key] = '';
		});
	}
	const confirmChange = (val) => {
		courseName.value = val.value[0].courseName || ''
		// console.log(val)
		formsubmit.courseId = val.value[0].courseId
		show.value = false
	}

	// 登录
	const submitLogin = () => {
		if (!idCardChange() && pageType.value != 'seller') {
			return
		}
		if (pageType.value == 'seller') {
			if (!isMobile(formsubmit.mobile)) {
				uni.showToast({
					title: '手机号格式错误',
					duration: 1200,
					icon: "none"
				});
				return
			}
			if (!formsubmit.password) {
				uni.showToast({
					title: '请输入密码',
					duration: 1200,
					icon: "none"
				});
				return
			}
			let JPQUrl = 'pages/index/index'
			let ZJXTUrl = 'pages/index/index-zj'
			console.log(proxy.getProjectCode(), 'code')
			let request = {
				"mobile": '',
				"password": ""
			}
			for (let key in request) {
				request[key] = formsubmit[key]
			}
			saleLogin(request).then((res) => {
				uni.setStorageSync('token', res.data.sessionKey)
				uni.setStorageSync('loginType', 'seller')
				proxy.$u.route({
					type: 'redirect',
					url: proxy.getProjectCode() === 'ZJXT' ? ZJXTUrl : JPQUrl,
				})
			})
		} else {
			if (!formsubmit.password) {
				uni.showToast({
					title: '请输入密码',
					duration: 1200,
					icon: "none"
				});
				return
			}
			loginHandle();
		}
	}
	const loginReq = (wechatCode, bandOpenId) => {
		formsubmit.code = wechatCode;
		formsubmit.bingFlag = bandOpenId ? 1 : 0;
		if (!isWechatApp()) {
			formsubmit.openIdFlag = 0;
		}
		login(formsubmit, loginFailHandle).then((res) => {
			uni.setStorageSync('idCard', res.data.idCard)
			uni.setStorageSync('token', res.data.sessionKey)
			uni.setStorageSync('loginType', 'student')
			proxy.$u.route({
				type: 'redirect',
				url: 'tabBarPages/index/index'
			})
		})
	}
	const dialogConfirmHandle = () => {
		uni.login({
			success: res => {
				let wechatCode = res.code;
				loginReq(wechatCode, true);
			}
		});
		showConfirmDialog.value = false;
	}
	const dialogCancelHandle = () => {
		uni.login({
			success: res => {
				let wechatCode = res.code;
				loginReq(wechatCode, true);
			}
		});
		showConfirmDialog.value = false;
	}
	const loginHandle = () => {
		if (isWechatApp()) {
			uni.login({
				success: res => {
					let wechatCode = res.code;
					loginReq(wechatCode, true);
				}
			});
		} else {
			loginReq('', false);
		}
	}
	const loginFailHandle = (res) => {
		if (res.code == 5001) {
			showConfirmDialog.value = true;
		} else {
			uni.showToast({
				mask: true,
				title: res.msg,
				duration: 1200,
				icon: 'none'
			})
			// 登录失效退回首页
			if (res.code == 401) {
				uni.clearStorageSync();
				uni.$u.route({
					type: 'redirect',
					url: '/pages/login/login'
				})
			}
		}
	}
	const isWechatApp = () => {
		return uni.getSystemInfoSync().platform === 'mp-weixin';
	}
</script>
<style scope lang="scss">
	.u-input {
		&__content {
			&__field-wrapper {
				&__field {
					// height: 50px !important;
				}
			}
		}
	}

	.forget-password {
		position: absolute;
		font-size: 14px;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		margin-top: 130px;
		color: #D3D3D3;
		width: 100%;

		text {
			float: right;
		}
	}

	.seller-button {
		font-size: 14px;
		text-align: center;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		width: 70px;
		margin: 25px auto 0 auto;
		color: #999999;
		border-bottom: 1px solid;
	}

	.u-button--primary {
		background-color: #366DE8;
		border-color: #366DE8
	}

	.selectView {
		background: #fff;
		border: none;
		width: 92%;
		padding: 16px 15px;
		border-radius: 4px;
		margin-top: 1.25rem;
		// border: 0.5px solid #dadbde;
	}

	.login-title {
		position: relative;
		font-size: 70rpx;
		font-family: Alimama ShuHeiTi;
		font-weight: bold;
		color: #333333;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.tip-bg {
			width: 56px;
			height: 20px;
			left: 75px;
			top: 0px;
			position: absolute;

			image {
				position: absolute;
			}

			text {
				position: absolute;
				top: 1px;
				left: 10px;
				font-size: 12px;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #FFFFFF;
			}
		}
	}

	.u-submit-form {
		display: flex;
		flex-direction: column;
		align-items: center;
		/* transform: translateY(-300rpx); */
		/* margin: 140rpx 0 264rpx 0; */
		margin: 2.5875rem 0 2.6875rem 0;
	}

	.w-100 {
		width: 100%;
	}

	.u-button-login {
		width: 100%;
		position: absolute;
		//bottom: 13.875rem;
		top: 20%
	}
</style>